package com.jinyijia.api.rest.v2.region;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @author WX
 * @date 2018/10/8
 **/
@RestController
@RequestMapping("/regions")
public class RegionController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    public RegionController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /*{
        province_list: {
            110000: '北京市',
            120000: '天津市'
        },
        city_list: {
            110100: '北京市',
            110200: '县',
            120100: '天津市',
            120200: '县'
        },
        county_list: {
            110101: '东城区',
            110102: '西城区',
            110105: '朝阳区',
            110106: '丰台区'
            120101: '和平区',
            120102: '河东区',
            120103: '河西区',
            120104: '南开区',
            120105: '河北区',
            // ....
        }
    }*/
    @GetMapping(value = "/tree", produces = "application/json")
    public String tree() {
        return JSON.toJSONString(getRegion()).replace("province", "province_list").replace("city", "city_list").replace("county", "county_list");
    }

    public Region getRegion() {
        return Optional.ofNullable(region).orElseGet(() -> {
            initRegion();
            return region;
        });
    }

    private void initRegion() {
        region = new Region();
        Set<RegionTreeDTO> regionTreeDTOSet = restTemplate.exchange("http://region-service/regions/tree", HttpMethod.GET, null, new ParameterizedTypeReference<Set<RegionTreeDTO>>() {
        }).getBody();
        put(1, "", regionTreeDTOSet);
    }

    private void put(int level, String parentKey, Set<RegionTreeDTO> regionTreeDTOSet) {
        if (level > 3) {
            return;
        }
        Map<String, String> levelMap = level == 1 ? region.getProvince() : (level == 2 ? region.getCity() : region.getCounty());
        int count = 10;
        for (RegionTreeDTO tree : regionTreeDTOSet) {
            String key = parentKey + (count++);
            levelMap.put(key, tree.getName());
            put(level + 1, key, tree.getChildren());
        }
    }

    private static Region region;

    @Data
    public class Region {
        Map<String, String> province = new HashMap<>();
        Map<String, String> city = new HashMap<>();
        Map<String, String> county = new HashMap<>();
    }


}
